<?php
/**
 * FastApp.
 * 12/29/24
 * @Author deepsea159
 * @Contact telegram:deepsea159
 */

namespace App\Fastapp\Api\Service\Account;

use App\Fastapp\Api\Service\BaseService;
use App\Fastapp\Exception\TipException;
use App\Fastapp\Model\AccountPayInfo;

class PayInfoService extends BaseService
{
    public function list(array $param): array
    {
        $map['user_id'] = get_uid();
        $query = AccountPayInfo::query();
        if (isset($param['type']) && is_numeric($param['type'])) $map['type'] = $param['type'];
        $paginate = $query->where($map)->orderByDesc('id')->simplePaginate();
        return ['list' => $paginate->items()];
    }

    public function create(array $param): array
    {
        $param['user_id'] = get_uid();
        $param['account_type'] = get_user_cache('type', $param['user_id']);
        $map = [
            'user_id' => $param['user_id'],
            'type' => $param['type'],
            'no' => $param['no']
        ];
        $md = AccountPayInfo::query()->where($map)->first();
        if ($md) {
            if ($md->is_lock) return $md->toArray();
        } else {
            $map['account_type'] = $param['account_type'];
            $map['is_lock'] = 1;
            unset($map['user_id']);
            if (AccountPayInfo::query()->where($map)->exists()) throw new TipException(fastapp_t('account.pay_info_lock'));
            $md = new AccountPayInfo();
        }
        $md->fill($param);
        $md->save();
        return $md->toArray();
    }

    public function del(array $ids): bool
    {
        return AccountPayInfo::query()->where(['user_id' => get_uid(), 'is_lock' => 0])->whereIn('id', $ids)->delete();
    }
}